package com.gege.homework9.datasource;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author gechenpeng
 * @date 2021-05-21
 */
@Component
@Aspect
public class DataSourceAspect {

    @Pointcut("@annotation(com.gege.homework9.datasource.CurDataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        CurDataSource curDataSource = method.getAnnotation(CurDataSource.class);

        if (null == curDataSource || StringUtils.isBlank(curDataSource.name())) {
            DynamicDataSource.setDataSource(DataSourceNames.FIRST);
        } else {
            DynamicDataSource.setDataSource(curDataSource.name());
        }

        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }
}
